package com.tinckay.common.aspect;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.tinckay.common.annotation.Log;
import com.tinckay.common.constant.LogType;
import com.tinckay.common.constant.ProjectConstant;
import com.tinckay.common.exception.ServiceException;
import com.tinckay.common.log.LogManager;
import com.tinckay.common.log.factory.LogTaskFactory;
import com.tinckay.common.util.AddressUtils;
import com.tinckay.common.util.HttpContextUtils;
import com.tinckay.common.util.IPUtils;
import com.tinckay.common.util.ShiroUtils;
import com.tinckay.entity.po.SysLog;
import com.tinckay.entity.po.User;
import com.tinckay.service.SysLogService;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.LocalVariableTableParameterNameDiscoverer;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;


/**
 * @author yuanjie
 */
@Aspect
@Component
public class LogAspect {

    Logger logger = LoggerFactory.getLogger(LogAspect.class);

    @Autowired
    private SysLogService sysLogService;
    @Autowired
    private ObjectMapper mapper;

    @Pointcut("@annotation(com.tinckay.common.annotation.Log)")
    public void pointcut() {
    }

    @Around("pointcut()")
    public Object around(ProceedingJoinPoint point) throws Throwable {
        long beginTime = System.currentTimeMillis();
        Object result = point.proceed();
        long time = System.currentTimeMillis() - beginTime;
        try {
            saveLog(point, time);
        } catch (Exception e) {
            logger.warn(e.getMessage());
        }
        return result;
    }

    private void saveLog(ProceedingJoinPoint joinPoint, long time) throws JsonProcessingException {
        User user = ShiroUtils.getCurrentUser();
        //如果当前用户未登录，不做日志
        if (null == user) {
            return;
        }
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();
        Log sysLogAnnotation = method.getAnnotation(Log.class);

        String operation = "";
        LogType logType;
        if (sysLogAnnotation != null) {
            operation = sysLogAnnotation.value();
            logType = sysLogAnnotation.logType();
        }
        String className = joinPoint.getTarget().getClass().getName();
        String methodName = signature.getName();
        methodName = className + "." + methodName + "()";

        Object[] args = joinPoint.getArgs();
        LocalVariableTableParameterNameDiscoverer u = new LocalVariableTableParameterNameDiscoverer();
        String[] paramNames = u.getParameterNames(method);
        String paramsResult = "";
        if (args != null && paramNames != null) {
            StringBuilder params = new StringBuilder();
            for (int i = 0; i < args.length; i++) {
                params.append("  ").append(paramNames[i]).append(": ").append(this.mapper.writeValueAsString(args[i]));
            }
            paramsResult = params.toString();
        }

        String ipAddr = IPUtils.getIpAddr(HttpContextUtils.getHttpServletRequest());
        LogManager.me().executeLog(LogTaskFactory.sysLog(sysLogAnnotation.logType(), user, operation, time, methodName, paramsResult, ipAddr));
    }
}
